import { utilJs } from "@/utils/common.js";
function initReport() {
  window.ckjrReportData = report;
}
/**
 *
 *数据埋点上报
 * @param {*} [data={}]
 * @param {boolean} [isClosePage=false] 是否关闭页面前发送数据
 */
function report(data = {}, isClosePage = false) {
  let isTest = window.location.href.indexOf('http://kptest') > -1 || window.location.href.indexOf('https://kptest') > -1;
  let reportUrl = isTest ? 'https://stat-cs.myckjr.com/report' : 'https://stat.ckjr001.com/report';
  let reData = data;
  let urlArr = window.location.href.split('#');
  let encodeUrl = urlArr.length > 1 ? encodeURIComponent(urlArr[1]) : '';//url 为 # 后的部分（包含所有 query string）
  let userId = localStorage.getItem('userId') == '' ? -100 : localStorage.getItem('userId');
  let companyId = localStorage.getItem('companyId');
  let isIosApp = navigator.userAgent.indexOf("IOSLogin") > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1;
  let isAndroidApp = navigator.userAgent.indexOf("APPLogin") > -1;
  let chl = isIosApp ? 'ios' : isAndroidApp ? 'droid' : 'gxh';//chl 为端名：公众号 gxh，小程序 xcx，ios，安卓 droid, pc
  let headerConfig = {
    'X-DMP': `u=${userId}&c=${companyId}&url=${encodeUrl}&chl=${chl}`,
    'Authorization': `Bearer ${localStorage.getItem("token")}`,
    'X-STORE-ID' : utilJs.getStoreId(),
    'X-From': 'oa',
  }
  if (isClosePage) {
    berforeCloseSendData(reportUrl, reData, headerConfig);
  } else {
    xhrGetMethod(reportUrl, reData, headerConfig);
  }
}
//关闭页面前发送数据
function berforeCloseSendData(url, data, config = {}) {
  let postData = new FormData();
  let urlParam = url.includes('?') ? '&' : '?';
  for (let key in data) {
    postData.append(key, data[key]);
    urlParam += `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}&`;
  }
  urlParam = urlParam.substring(0, urlParam.length - 1);
  if (navigator.sendBeacon) {
    for (let key in config) {
      postData.append(key, config[key]);
    }
    postData.append('postMethods', 'sendBeacon');
    navigator.sendBeacon(url, postData);
  } else {
    postData.append('postMethods', 'get');
    let client = new XMLHttpRequest();
    client.open("GET", `${url}${urlParam}`, false); // 第三个参数表明是同步的 xhr
    for (let key in config) {
      client.setRequestHeader(key, config[key]);
    }
    client.send();
  }
}
function xhrGetMethod(url, data, config = {}) {
  let urlParam = url.includes('?') ? '&' : '?';
  for (let key in data) {
    urlParam += `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}&`;
  }
  urlParam = urlParam.substring(0, urlParam.length - 1);
  var request = new XMLHttpRequest();
  request.timeout = 0;
  request.open('GET', `${url}${urlParam}`);
  for (let key in config) {
    request.setRequestHeader(key, config[key]);
  }
  request.send()
}
export {
  initReport,
}
